package com.lee.rabbitmq.transaction;

import com.lee.rabbitmq.util.RabbitMqUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * 使用事务接收消息
 * @author Lee
 * @createDate 2021/12/14 16:07
 */
public class Receive {
    public static void main(String[] args) {
        Connection connection = RabbitMqUtil.getConnection();
        Channel channel = null;
        try {
            channel = connection.createChannel();
            //声明队列
            channel.queueDeclare("transactionQueue",true,false,false,null);
            //声明交换机
            channel.exchangeDeclare("directTransactionExchange","direct",true);
            //绑定交换机
            channel.queueBind("transactionQueue","directTransactionExchange","transactionRoutingKey");

            /**
             * 开启事务
             * 当消费者开启事务以后，即使不作为事务的提交，那么依然可以获取队列中的消息并且将消息从队列中移除掉
             * 注意:
             *  暂时事务队列接收者没有任何的影响
             */
            channel.txSelect();
            channel.basicConsume("transactionQueue",true,new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body);
                    System.out.println("消费者: "+message);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
